﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Data;
using Gift.Model.ENUM;
using System.Text;
using Gift.DAL;
using Gift.Model;

namespace WebSite.admin.product
{
    public partial class OpenCard : BaseAdmin
    {
        readonly dalCompany theCompany = new dalCompany();
        readonly DALAdminLogin theAdminLogin = new DALAdminLogin();
        readonly DALCardType theCardType = new DALCardType();

        // Methods
        private void Bind()
        {
            if ((base.Request.QueryString["cid"] != null) && (base.Request.QueryString["action"] != null))
            {
                if (base.Request.QueryString["action"].ToString() == "del")
                {
                    SQLAccess.DoSql("delete from DB_Card where cardid=" + base.Request.QueryString["cid"].ToString() + "");
                }
                base.Response.Write("<script language='javascript'>window.location.href='card.aspx';</script>");
                base.Response.End();
            }
        }
        private void BindProfessionAreaType()
        {
            DataSet dsType = new DataSet();
            DALProfessionAreaType theType = new DALProfessionAreaType();
            dsType = theType.GetList("");
            if (dsType.Tables.Count > 0)
            {
                this.ddlProfessionAreaType.DataSource = dsType.Tables[0].DefaultView;
                this.ddlProfessionAreaType.DataTextField = "Name";
                this.ddlProfessionAreaType.DataValueField = "Id";
                this.ddlProfessionAreaType.DataBind();
            }
            this.ddlProfessionAreaType.Items.Insert(0, new ListItem("所属专区", ""));


        }


        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = this.ddlCurrentPage.SelectedIndex;
            this.GridViewBind("");
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {



            if ((e.Row.RowType == DataControlRowType.Header) || (e.Row.RowType == DataControlRowType.DataRow))
            {
                CheckBox box = new CheckBox();
                box = (CheckBox)e.Row.FindControl("CheckBox1");
              
                if (box != null)
                {
                    if (e.Row.RowType == DataControlRowType.DataRow)
                    {
                        if (base.CompanyId != null)
                        {
                            LinkButton lbEnable = new LinkButton();
                            lbEnable = e.Row.FindControl("lbtnDisable") as LinkButton;
                            lbEnable.Visible = false;
                            LinkButton lbCancel = new LinkButton();
                            lbCancel = e.Row.FindControl("lbtnCancel") as LinkButton;
                            lbCancel.Visible = false;
                        }


                        if (e.Row.Cells[6].Text == ((int)CardState.AlreadyOpen).ToString() || e.Row.Cells[6].Text == "5")
                        {
                            e.Row.Cells[6].Text = "已开卡";
                        }
                        else if (e.Row.Cells[6].Text == ((int)CardState.AlreadyUserd).ToString())
                        {
                            e.Row.Cells[6].Text = "已使用";
                        }
                        else if (e.Row.Cells[6].Text == ((int)CardState.AlreadyDisable).ToString())
                        {
                            e.Row.Cells[6].Text = "已失效";
                        }
                        else if (e.Row.Cells[6].Text == ((int)CardState.NoProduct).ToString())
                        {
                            e.Row.Cells[6].Text = "未生产";
                        }
                        else if (e.Row.Cells[6].Text == ((int)CardState.NoOpen).ToString())
                        {
                            e.Row.Cells[6].Text = "未激活";
                        }
                        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=\"" + e.Row.Style["BACKGROUND-COLOR"] + "\"");
                        e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor=\"#efefef\"");
                    }
                    else if (e.Row.RowType == DataControlRowType.Header)
                    {
                        box.Attributes.Add("onclick", "SelectAll(this.checked)");
                    }
                    //e.Row.Cells[9].Visible = false;
                }
            }
        }

        protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sqlsort = "";
            //sqlsort = "select * from DB_Card";
            this.GridViewBind(sqlsort);
        }

        private void GridViewBind(string Sqlsort)
        {
            string sStates = " and states = " + this.ddlStates.SelectedItem.Value;

            if (this.ddlStates.SelectedItem.Value == "1")
            {
                sStates = " and states in (1,5)";
            }

            string sql = "select *,'" + this.ddlStates.SelectedItem.Text + "' as statesName, (select Name from tbCardType where Id = DB_Card.CardTypeId) as CardTypeName,(select Name from tbCompany where Id=DB_Card.companyId) as companyName  from DB_Card where 1=1 "
                         + sStates;


            if (!LoginAdminUser.IsSuper || !string.IsNullOrEmpty(this.ddlInstitution.SelectedItem.Value))
            {
                if (!LoginAdminUser.IsSuper)
                {
                    sql = sql + " and InstitutionId = " + LoginAdminUser.InstitutionId;
                }
                else
                {
                    sql = sql + " and InstitutionId = " + this.ddlInstitution.SelectedItem.Value;
                }
            }

            if(this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ";
                }
                catch
                {
                   
                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ";
                }
                catch
                {

                }
            }
            if (base.CompanyId != null)
            {
                sql = sql + " and companyId = " + base.CompanyId;
            }else  if (this.ddlCompany0.SelectedItem.Value.Trim() != "")
            {
                sql = sql + " and companyId = " + this.ddlCompany0.SelectedItem.Value.Trim() ;
            }

            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            }
           

            sql = sql + " order by cardid desc";
        
            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];
            this.GridView1.DataSource = table.DefaultView;
            this.GridView1.DataBind();
            this.LblCurrentIndex.Text = "当前第 " + ((this.GridView1.PageIndex + 1)).ToString() + "页";
            this.LblPageCount.Text = "共 " + this.GridView1.PageCount.ToString() + "页";
            this.LblRecordCount.Text = "总计 " + table.Rows.Count.ToString() + "个记录";
            if (table.Rows.Count == 0)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = false;
                this.LblPageCount.Visible = false;
                this.LblRecordCount.Visible = false;
            }
            else if (this.GridView1.PageCount == 1)
            {
                this.btnFirst.Visible = false;
                this.btnPrev.Visible = false;
                this.btnNext.Visible = false;
                this.btnLast.Visible = false;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            } else{

                this.btnFirst.Visible = true;
                this.btnPrev.Visible = true;
                this.btnNext.Visible = true;
                this.btnLast.Visible = true;
                this.LblCurrentIndex.Visible = true;
                this.LblPageCount.Visible = true;
                this.LblRecordCount.Visible = true;
            }
            this.btnFirst.CommandName = "1";
            this.btnPrev.CommandName = (this.GridView1.PageIndex == 0) ? "1" : this.GridView1.PageIndex.ToString();
            this.btnNext.CommandName = (this.GridView1.PageCount == 1) ? this.GridView1.PageCount.ToString() : ((this.GridView1.PageIndex + 2)).ToString();
            this.btnLast.CommandName = this.GridView1.PageCount.ToString();
            this.ddlCurrentPage.Items.Clear();
            for (int i = 1; i <= this.GridView1.PageCount; i++)
            {
                this.ddlCurrentPage.Items.Add(i.ToString());
            }
            if (ddlCurrentPage.Items.Count > 0)
            {
                this.ddlCurrentPage.SelectedIndex = this.GridView1.PageIndex;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
         
            if (!base.IsPostBack)
            {

                if (base.CompanyId != null)
                {
                    this.ibtnExport.Visible = false;
                    this.tdUpdateCompany.Visible = false;
                    this.tdCompany.Visible = false;
                    this.tdCompanySelect.Visible = false;
                    this.ddlStates0.Visible = false;
                    this.ibtnOpenCard0.Visible = false;
                    this.FileUpload1.Visible = false;
                    this.btnExport0.Visible = false;
                    this.tdExport.Visible = false;
                }
                else
                {
                    base.ValidateLoginRule(ERule.OpenCardManager);
                }
                this.BindProfessionAreaType();
                this.BindCompanyList();
                this.BindInstitution();
                this.Bind();
                this.GridViewBind("");

             
            }
        }

        protected void PagerButtonClick(object sender, EventArgs e)
        {
            this.GridView1.PageIndex = Convert.ToInt32(((LinkButton)sender).CommandName) - 1;
            this.GridViewBind("");
        }

        protected void ibtnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.GridViewBind("");
        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "open")
            {

                int id = int.Parse(this.GridView1.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());
                SQLAccess.DoSql("update DB_Card set states=1  where cardid=" + id.ToString() + " and states != 2");
                Response.Write("<script language=javascript>alert('修改成功！');</script>");
                this.GridViewBind("");

            }
            else if (e.CommandName == "disable")
            {
                int id = int.Parse(this.GridView1.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());
                SQLAccess.DoSql("update DB_Card set states=3 where cardid=" + id.ToString() + " and states!=2");
                Response.Write("<script language=javascript>alert('修改成功！');</script>");
                this.GridViewBind("");
            }
            else if (e.CommandName == "cance")
            {
                int id = int.Parse(this.GridView1.DataKeys[int.Parse(e.CommandArgument.ToString())].Value.ToString());
                SQLAccess.DoSql("update DB_Card set states=4 where cardid=" + id.ToString() + " and states!=2");
                Response.Write("<script language=javascript>alert('修改成功！');</script>");
                this.GridViewBind("");
            }
        }

        protected void ibtnExport_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select cardcode as 卡号,cardprice as 金额,"
                        + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                         + " convert(varchar(10),starttime,121) as 专区开始日期, "
                        + " convert(varchar(10),endtime,121) as 专区截止日期,  convert(varchar(10),lasttime,121) as 礼品商城截止日期,"
                        + " (select [Name] from tbCompany where id= DB_Card.companyId) as 经销商 "
                        +" from DB_Card where 1=1 "
                        + " and states = " + this.ddlStates.SelectedItem.Value;
            if (this.cardcodeFrom.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeFrom.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) >= " + this.cardcodeFrom.Value.Trim() + " ";
                }
                catch
                {

                }
            }
            if (this.cardcodeTo.Value.Trim() != "")
            {
                try
                {
                    decimal.Parse(this.cardcodeTo.Value.Trim());
                    sql = sql + " and convert(decimal,cardcode) <= " + this.cardcodeTo.Value.Trim() + " ";
                }
                catch
                {

                }
            }

            if (!LoginAdminUser.IsSuper || !string.IsNullOrEmpty(this.ddlInstitution.SelectedItem.Value))
            {
                if (!LoginAdminUser.IsSuper)
                {
                    sql = sql + " and InstitutionId = " + LoginAdminUser.InstitutionId;
                }
                else
                {
                    sql = sql + " and InstitutionId = " + this.ddlInstitution.SelectedItem.Value;
                }
            }


            if (base.CompanyId != null)
            {
                sql = sql + " and companyId = " + base.CompanyId;
            }
            else if (this.ddlCompany0.SelectedItem.Value.Trim() != "")
            {
                sql = sql + " and companyId = " + this.ddlCompany0.SelectedItem.Value.Trim();
            }

            if (this.ddlProfessionAreaType.SelectedItem.Value != "")
            {
                sql = sql + " and CardTypeId in(select id from tbCardType where ProfessionAreaTypeId = " + this.ddlProfessionAreaType.SelectedItem.Value + ")";
            }

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);
            //HttpContext curContext = System.Web.HttpContext.Current;
            //curContext.Response.ContentType = "application/vnd.ms-excel";
            //curContext.Response.ContentEncoding = System.Text.Encoding.Default;
            //curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
            //curContext.Response.Charset = "";
            //curContext.Response.Write(BuildExportHTML(table));
            //curContext.Response.Flush();
            //curContext.Response.End();
        }

        private string BuildExportHTML(DataTable dt)
        {

            string result = string.Empty;
            int readCnt = dt.Rows.Count;
            int colCount = dt.Columns.Count;

            int pagerecords = 10000;
            string strTitleRow = "";
            for (int j = 0; j < colCount; j++)
            {
                strTitleRow += dt.Columns[j].ColumnName + "\t";
            }
            strTitleRow += "\r\n";

            StringBuilder strRows = new StringBuilder();
            int cnt = 1;
            for (int i = 0; i < readCnt; i++)
            {
                //strRows.Append("");
                for (int j = 0; j < colCount; j++)
                {
                    if (dt.Columns[j].DataType.Name == "DateTime" || dt.Columns[j].DataType.Name == "SmallDateTime")
                    {
                        if (dt.Rows[i][j].ToString() != string.Empty)
                        {
                            strRows.Append(Convert.ToDateTime(dt.Rows[i][j].ToString()).ToString("yyyy-MM-dd") + "\t");
                        }
                        else
                            strRows.Append("\t");
                    }
                    else
                    {
                        strRows.Append(dt.Rows[i][j].ToString().Trim() + "\t");
                    }
                }
                strRows.Append("\r\n");
                cnt++;
                if (cnt >= pagerecords)
                {
                    result += strRows.ToString();
                    strRows.Remove(0, strRows.Length);
                    cnt = 1;
                }
            }
            result = strTitleRow + result + strRows.ToString();
            return result;
        }

        void BindCompanyList()
        {
            string sWhere = string.Empty;
            if (!LoginAdminUser.IsSuper)
            {
                sWhere = " and InstitutionId = " + LoginAdminUser.InstitutionId.ToString();
            }

            DataSet dsCompany = theCompany.GetList("CompanyTypeId=1" + sWhere);
            this.ddlCompany.DataTextField = "Name";
            this.ddlCompany.DataValueField = "Id";
            this.ddlCompany.DataSource = dsCompany.Tables[0].DefaultView;
            this.ddlCompany.DataBind();
            this.ddlCompany.Items.Insert(0, new ListItem("所属经销商", ""));
            this.ddlCompany0.DataTextField = "Name";
            this.ddlCompany0.DataValueField = "Id";
            this.ddlCompany0.DataSource = dsCompany.Tables[0].DefaultView;
            this.ddlCompany0.DataBind();
            this.ddlCompany0.Items.Insert(0, new ListItem("所属经销商", ""));
        }

        protected void ibtnUpdateCompany_Click(object sender, ImageClickEventArgs e)
        {

            string companyId = "";
            companyId = this.ddlCompany.SelectedItem.Value == "" ? "0" : this.ddlCompany.SelectedItem.Value;
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    SQLAccess.DoSql("update DB_Card set companyId=" + companyId  + " where cardid=" + this.GridView1.DataKeys[i].Value + "");
                }
            }
            Response.Write("<script language=javascript>alert('批量更新经销商成功！');</script>");
            this.GridViewBind("");
        }

        protected void ibtnOpenCard_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    SQLAccess.DoSql("update DB_Card set states=1 where cardid=" + this.GridView1.DataKeys[i].Value + " and states!=2");
                }
            }
            Response.Write("<script language=javascript>alert('批量激活成功！');</script>");
            this.GridViewBind("");
        }

        protected void ibtnInport_Click(object sender, ImageClickEventArgs e)
        {
            if (this.FileUpload1.FileContent.Length <= 0)
            {
                Response.Write("<script>alert('请选择要导入的EXCEL文件！')</script>");
                return;
            }
            else
            {
                try
                {
                    string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
                    this.FileUpload1.SaveAs(Server.MapPath("../uploadTempFile/" + fileName));

                    DataTable dtResult = new DataTable();

                    dtResult = Gift.Utile.OperateExcel.InputCSV( Server.MapPath("../uploadTempFile/" + fileName));


                    DataRow[] dr = dtResult.Select();
                    int ss = dtResult.Rows.Count;
                    int rowsnum = dtResult.Rows.Count;
                    if (rowsnum == 0)
                    {
                        Response.Write("<script>alert('Excel表为空表,无数据！')</script>");
                        return;
                    }
                    int iInportSum = 0;
                    
                    for (int i = 0; i < rowsnum; i++)
                    {
                        string cardtypeId = "0";
                        tbCardType oCardType = theCardType.GetModelByName(dr[i][3].ToString());
                        if (oCardType != null)
                        {
                             cardtypeId = oCardType.CardTypeId.ToString();
                        }
                       
                        string cardcode = dr[i][0].ToString();
                        string cardpass = dr[i][1].ToString();
                        string cardprice = dr[i][2].ToString()=="" ? "0" : dr[i][2].ToString();
                        string starttime = dr[i][4].ToString();
                        string endtime = dr[i][5].ToString();
                        string lasttime = dr[i][6].ToString();
                        string companyid = "0";
                        if (dr[i].ItemArray.Length > 6)
                        {
                            tbCompany oCompany = theCompany.GetModelByName(dr[i][6].ToString());
                            if (oCompany != null)
                            {
                                companyid = oCompany.Id.ToString();
                            }
                        }

                        string sql = " if exists(select 1 from DB_Card where cardcode = '" + cardcode + "') "
                                    + " begin "
                                     + " update DB_Card  set cardtypeid = " + cardtypeId
                                     + " ,cardprice = " + cardprice
                                     + " ,starttime = '" + starttime + "'"
                                     + " ,lasttime='" + lasttime + "'"
                                     + ", companyid = " + companyid
                                     + " where cardcode = '" + cardcode + "'"
                                     + " end"
                                     + " else"
                                     + " begin "
                                     + " insert into DB_Card(cardtypeId,cardcode,cardpas,cardprice,starttime,endtime,states,companyid,lasttime)"
                                     + " values(" + cardtypeId + ",'" + cardcode + "','" + cardpass + "'," + cardprice +",'" + starttime + "','" + endtime + "',4," + companyid + ",'" + lasttime + "')"
                                     + " end";
                                                 SQLAccess.DoSql(sql);
                            iInportSum++;
                     
                    }
                    Response.Write("<script>alert('成功导入" + iInportSum.ToString() + "条礼品卡记录！')</script>");
                    this.Dispose();
                    this.GridViewBind("");
                }
                catch (Exception ex)
                {
                    Response.Write("出错了：" + ex.ToString() );
                }
            }

        }

        protected void ibtnExport0_Click(object sender, ImageClickEventArgs e)
        {
            string sql = "select top 0 cardcode as 卡号,cardpas as 密码,cardprice as 金额,"
                      + " (select [Name] from tbCardType where id= CardTypeId) as 礼品卡类别,"
                       + " convert(varchar(10),starttime,121) as 专区开始日期,"
                      + " convert(varchar(10),endtime,121) as 专区截止日期,convert(varchar(10),lasttime,121) as 礼品商城截止日期 ,'' as 经销商 from DB_Card where 1=1 ";
          

            DataTable table = new DataTable();
            table = SQLAccess.GreatDs(sql).Tables[0];

            string fileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";//设置导出文件的名称
            Gift.Utile.OperateExcel.ExportCSV(table, fileName);
        }

        protected void ibtnOpenCard0_Click(object sender, ImageClickEventArgs e)
        {
            for (int i = 0; i <= (this.GridView1.Rows.Count - 1); i++)
            {
                CheckBox box = (CheckBox)this.GridView1.Rows[i].FindControl("CheckBox1");
                if (box.Checked)
                {
                    SQLAccess.DoSql("update DB_Card set states=" + this.ddlStates0.SelectedItem.Value + " where cardid=" + this.GridView1.DataKeys[i].Value + " and states!=2");
                }
            }
            Response.Write("<script language=javascript>alert('批量更新状态成功！');</script>");
            this.GridViewBind("");
        }


        protected void ibtnStoreOut_Click(object sender, ImageClickEventArgs e)
          {
              if (string.IsNullOrEmpty(this.ddlCompany0.SelectedItem.Value))
              {
                  Response.Write("<script language=javascript>alert('请选取经销商！');</script>");
                  return;
              }
              Response.Redirect("StoreOut.aspx?companyid=" + this.ddlCompany0.SelectedItem.Value + "&cardCodeFrom=" + this.cardcodeFrom.Value + "&cardCodeTo=" + this.cardcodeTo.Value);
 
          }


        private void BindInstitution()
        {
            if (LoginAdminUser.IsSuper)
            {
                this.ddlInstitution.Visible = true;
                DataSet ds = new DataSet();
                DALInstitution theInstitution = new DALInstitution();
                ds = theInstitution.GetList("");
                if (ds.Tables.Count > 0)
                {
                    this.ddlInstitution.DataSource = ds.Tables[0].DefaultView;
                    this.ddlInstitution.DataTextField = "Name";
                    this.ddlInstitution.DataValueField = "Id";
                    this.ddlInstitution.DataBind();
                }
                this.ddlInstitution.Items.Insert(0, new ListItem("所属公司", ""));
            }
            else
            {
                this.ddlInstitution.Visible = false;
            }
        }

    }
}